//
//  MGRecordsController.m
//  MoneyRecord_iOS
//
//  Created by alchemy on 2022/1/8.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGRecordsController.h"
#import "MGRecordController.h"
#import "MGRecordsSelectController.h"
#import "MGReceiptController.h"
#import "MGPunchController.h"
#import "MGAccountController.h"
#import "MGAccountsController.h"
#import "MGCategoryController.h"
#import "MGCategoriesController.h"
#import "MGAccountIconController.h"
#import "MGLoginController.h"
#import "MGDateRecordsController.h"

#import "MGRecordsHeaderView.h"
#import "MGGradientView.h"
#import "MGRecordsNavigationView.h"
#import "MG365RecordsView.h"

#import "MGRecordsReceiptCell.h"
#import "MGRecordsDateCell.h"
#import "MGReceiptEmptyCell.h"

#import "MGAlertManager.h"

@interface MGRecordsController ()
@property (nonatomic, strong) YYBAlertView *dataQueryAlertView;

@property (nonatomic, strong) MGRecordsHeaderView *headerView;
@property (nonatomic, strong) MGGradientView *gradientView;
@property (nonatomic, strong) MGRecordsNavigationView *navigationView;
@property (nonatomic, strong) MGAlertView *emptyAlertView;

@property (nonatomic, strong) MGRecordModel *selectRecordModel;
@property (nonatomic, strong) NSDate *selectedMonth;
// 选中的账户与类型
@property (nonatomic) NSUInteger selectCategoryUniqueId;
@property (nonatomic) NSUInteger selectAccountUniqueId;

@property (nonatomic, strong) NSMutableArray *sortedReceiptModels;
@property (nonatomic) BOOL shouldOpenCategory, shouldOpenAccount;
@property (nonatomic) BOOL shouldUpdateList;
@property (nonatomic) BOOL shouldRemoveBottomInsets;

// ============== 365模式
@property (nonatomic, strong) MG365RecordsView *recordGridView;

@end

@implementation MGRecordsController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHiddenNavigationBar = YES;
    self.tableView.showsVerticalScrollIndicator = NO;
    
//    if (!MGConfigManager.shared.dataModel.isStarted) {
//        [YYBViewRouter openOnClass:[MGLoginController class] configureBlock:nil isAnimated:NO appearType:YYBRouterAppearTypePresentWithNavigation navigationBlock:^(UINavigationController * _Nonnull nav) {
//            nav.modalPresentationStyle = UIModalPresentationFullScreen;
//        }];
//
//        [MGConfigManager.shared configWithBlock:^(MGConfigModel * _Nonnull dataModel) {
//            dataModel.isStarted = YES;
//        }];
//    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (self.shouldOpenCategory) {
        [self handleSelectCategory];
        self.shouldOpenCategory = NO;
    }
    
    if (self.shouldOpenAccount) {
        [self handleSelectAccount];
        self.shouldOpenAccount = NO;
    }
    
    if (self.shouldUpdateList) {
        [self refreshData];
        self.shouldUpdateList = NO;
    }
}

- (void)beforeConfigViewAction {
    [super beforeConfigViewAction];
    
    CGFloat navibarHeight = 44 + [UIDevice safeAreaInsetsTop];
    CGFloat height = kScreenHeight - navibarHeight - [UIDevice safeAreaInsetsBottom];
    self.recordGridView = [[MG365RecordsView alloc] initWithFrame:CGRectMake(0, navibarHeight, kScreenWidth, height)];
    
    @weakify(self);
    self.recordGridView.handleReceiptBlock = ^(MGReceiptModel * _Nonnull receiptModel) {
        @strongify(self);
        [self handle365TypeReceipt:receiptModel];
    };
    [self.view addSubview:self.recordGridView];
}

- (void)beginConfigViewAction {
    [super beginConfigViewAction];
    
    self.gradientView = [[MGGradientView alloc] init];
    self.gradientView.gradientLayer.locations = @[@0, @1];
    self.gradientView.gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor,
                                               (__bridge id)APP_COLOR_BACKGROUND.CGColor];
    [self.view insertSubview:self.gradientView belowSubview:self.tableView];
    [self.gradientView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // =====================
    self.navigationView = [MGRecordsNavigationView createViewAtSuperView:self.view constraintBlock:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(44 + [UIDevice safeAreaInsetsTop]);
    } configureBlock:nil];
    
    @weakify(self);
    self.navigationView.recordTapedBlock = ^{
        @strongify(self);
        [self handleRecordsSelect];
    };
    self.navigationView.dateTapedBlock = ^{
        @strongify(self);
        [YYBViewRouter openOnClass:[MGDateRecordsController class] configureBlock:^(MGDateRecordsController *obj) {
            obj.deleteSuccBlock = ^{
                self.shouldUpdateList = YES;
            };
            obj.updateSuccBlock = ^{
                self.shouldUpdateList = YES;
            };
        }];
    };
    
    self.headerView = [[MGRecordsHeaderView alloc] init];
    self.headerView.frame = CGRectMake(0, 0, kScreenWidth, 200);
    self.headerView.accountTapedBlock = ^{
        @strongify(self);
        [self handleSelectAccount];
    };
    self.headerView.categoryTapedBlock = ^{
        @strongify(self);
        [self handleSelectCategory];
    };
    self.tableView.tableHeaderView = self.headerView;
}

- (void)beginCreateNotifications {
    [super beginCreateNotifications];
    
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:MGNOTI_CREATERECEIPT object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self handleCreateReceipt];
    }];

    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:MGNOTI_REFRESH_DATA object:nil]
     subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self refreshData];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:YYBUserLogoutNotifictaion object:nil]
     subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self refreshData];
        // 清除残留数据
        [self.tableView reloadData];
    }];
    
    // 登录后，如果没有被上传的预算表，会自动上传
    // 登出后，如果有被上传的预算表，会删除
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:YYBUserLoginNotifictaion object:nil]
     subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [MGCommonAccessor.shared saveUnsyncDataToOssWithCompleteBlock:^{
            [self refreshData];
        } errorBlock:^(NSError *error) {
            [YYBAlertView showAlertViewWithError:error];
        }];
        
        // 自动获取数据
        self.dataQueryAlertView = [YYBAlertView showQueryStringAlertView];
        
        MGRecordModel *defaultModel = [MGRecordAccessor.shared getDefaultRecordModel];
        [MGCommonAccessor.shared getAndSaveAllOssDataWithCompleteBlock:^{
            if (defaultModel && defaultModel.receiptModels.count > 0) {
                [self.dataQueryAlertView closeAlertView];
                [self handleMergeRecordData];
            } else {
                [self refreshData];
                [MGAlertView closeAlertView:self.dataQueryAlertView showString:@"数据已从云端自动同步"];
            }
        } errorBlock:^(NSError *error) {
            [MGAlertView closeAlertView:self.dataQueryAlertView showError:error];
        }];
    }];
}

- (void)handleMergeRecordData {
    // 合并并且上传到oss成功后，才能删除本地的数据
    @weakify(self);
    self.refreshAlertView = [YYBAlertView showQueryAlertView];
    
    [MGRecordAccessor.shared mergeDefaultRecordModelsWithCompleteBlock:^{
        @strongify(self);
        [MGRecordAccessor.shared getLocalDataModels];
        [self refreshData];
        [MGAlertView closeAlertView:self.refreshAlertView showString:@"合并账本数据成功"];
    } errorBlock:^(NSError *error) {
        @strongify(self);
        [MGAlertView closeAlertView:self.refreshAlertView showError:error];
    }];
}

- (void)beginQueryData {
    [super beginQueryData];
    
    [self refreshData];
}

- (void)handle365TypeReceipt:(MGReceiptModel *)dataModel {
    NSString *shouldSaveMoneyStr = nil;
    CGFloat money = dataModel.shouldSaveMoney.floatValue;
    if (fmodf(money, 1) != 0) { // 有小数
        shouldSaveMoneyStr = [NSString stringWithFormat:@"%.1f",money];
    } else {
        shouldSaveMoneyStr = dataModel.shouldSaveMoney.stringValue;
    }
    shouldSaveMoneyStr = [NSString stringWithFormat:@"打卡金额￥%@", shouldSaveMoneyStr];
    
    if (dataModel.actualSaveTime != 0) {
        @weakify(self);
        [YYBAlertView showAlertViewWithTitle:shouldSaveMoneyStr detail:@"取消打卡吗？" firstActionTitle:@"取消" firstActionTapedBlock:^{

        } secondActionTitle:@"确定" secondActionTapedBlock:^{
            @strongify(self);
            MGReceiptModel *updateModel = [MGReceiptModel yy_modelWithJSON:dataModel.yy_modelToJSONObject];
            updateModel.actualSaveTime = 0;
            updateModel.savedMoney = [[NSDecimalNumber alloc] initWithFloat:0];
            [self handleUpdateReceipt:dataModel updateModel:updateModel];
        }];
    } else {
        @weakify(self);
        [YYBAlertView showAlertViewWithTitle:shouldSaveMoneyStr detail:@"确定打卡吗？" firstActionTitle:@"取消" firstActionTapedBlock:^{

        } secondActionTitle:@"确定" secondActionTapedBlock:^{
            @strongify(self);
            MGReceiptModel *updateModel = [MGReceiptModel yy_modelWithJSON:dataModel.yy_modelToJSONObject];
            updateModel.actualSaveTime = [NSDate date].timeIntervalSince1970;
            updateModel.savedMoney = updateModel.shouldSaveMoney;
            [self handleUpdateReceipt:dataModel updateModel:updateModel];
        }];
    }
}

- (void)handleUpdateReceipt:(MGReceiptModel *)receiptModel updateModel:(MGReceiptModel *)updateModel {
    @weakify(self);
    if (MGOssManager.shouldUpload) {
        self.refreshAlertView = [MGAlertView showLoadingWithString:@"保存中" inView:self.view];
    }
    [MGRecordAccessor.shared updateReceiptModel:receiptModel shouldUpdateModel:updateModel recordModel:self.selectRecordModel completeBlock:^{
        @strongify(self);
        [MGAlertView closeAlertView:self.refreshAlertView showString:@"保存成功"];
        [self refreshData];
    } errorBlock:^(NSError *error) {
        @strongify(self);
        [MGAlertView closeAlertView:self.refreshAlertView showError:error];
    }];
}

// 刷新数据
- (void)refreshData {
    if (self.emptyAlertView) {
        [self.emptyAlertView closeAlertView];
    }
    
    self.selectRecordModel = MGRecordAccessor.shared.getSelectedRecordModel;
    [self.navigationView configViewWithDataModel:self.selectRecordModel];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:MGNOTI_RECORDCHANGE object:nil];
    
    if (self.selectRecordModel) {
        if (self.selectRecordModel.recordType == MGRecordType365Money) {
            self.tableView.tableHeaderView = nil;
            self.recordGridView.hidden = NO;
            [self.recordGridView configViewWithDataModel:self.selectRecordModel];
        } else {
            self.tableView.tableHeaderView = self.headerView;
            self.recordGridView.hidden = YES;
            
            self.sortedReceiptModels = [self.selectRecordModel getSortedRecentReceiptModels:self.selectAccountUniqueId categoryUniqueId:self.selectCategoryUniqueId];
            [self.headerView configViewWithRecordModel:self.selectRecordModel accountUniqueId:self.selectAccountUniqueId categoryUniqueId:self.selectCategoryUniqueId];
        }
    } else {
        @weakify(self);
        CGFloat bottom = 49 + [UIDevice safeAreaInsetsBottom];
        UIEdgeInsets insets = UIEdgeInsetsMake(44 + [UIDevice safeAreaInsetsTop], 0, self.shouldRemoveBottomInsets ? 0 : bottom, 0);
        self.emptyAlertView = [MGAlertView showTextAlertViewInView:self.view text:@"请先添加账本" actionText:@"立即创建" insets:insets tapedActionBlock:^{
            @strongify(self);
            [self handleCreateRecordModel];
        }];
        self.shouldRemoveBottomInsets = NO;
    }
    
    [self.tableView reloadData];
}

// ====================================== 选择
// 选择账户
- (void)handleSelectAccount {
    @weakify(self);
    MGAccountModel *accountModel = [MGAccountAccessor.shared getAccountModelWithUniqueId:self.selectAccountUniqueId];

    [MGAlertView showAccountsAlertViewWithSelectModel:accountModel selectedBlock:^(MGAccountModel * _Nonnull dataModel) {
        @strongify(self);
        self.selectAccountUniqueId = dataModel.uniqueId;
        [self refreshData]; // 刷新所有数据
    } selectActionBlock:^(MGAlertViewActionType type) {
        @strongify(self);
        if (type == MGAlertViewActionTypeCreate) {
            self.shouldOpenAccount = YES;
            [self createAccount];
        } else if (type == MGAlertViewActionTypeList) {
            self.shouldOpenAccount = YES;
            [self getIntoAccountList];
        } else if (type == MGAlertViewActionTypeShowAll) {
            if (self.selectAccountUniqueId != 0) {
                self.selectAccountUniqueId = 0;
                [self refreshData];
            }
        }
    } shouldShowAllAccounts:YES isSelectAllAccounts:self.selectAccountUniqueId == 0 hidesAllActions:NO];
}

// 选择分类
- (void)handleSelectCategory {
    @weakify(self);
    MGCategoryModel *categoryModel = [MGCategoryAccessor.shared getCategoryModelWithUniqueId:self.selectCategoryUniqueId];
    
    [MGAlertView showCategoriesAlertViewWithSelectModel:categoryModel selectedBlock:^(MGCategoryModel * _Nonnull dataModel) {
        @strongify(self);
        self.selectCategoryUniqueId = dataModel.uniqueId;
        [self refreshData]; // 刷新所有数据
    } selectActionBlock:^(MGAlertViewActionType type) {
        @strongify(self);
        if (type == MGAlertViewActionTypeCreate) {
            self.shouldOpenCategory = YES;
            [self createCategory];
        } else if (type == MGAlertViewActionTypeList) {
            self.shouldOpenCategory = YES;
            [self getIntoCategoryList];
        } else if (type == MGAlertViewActionTypeShowAll) {
            if (self.selectCategoryUniqueId != 0) {
                self.selectCategoryUniqueId = 0;
                [self refreshData];
            }
        }
    } shouldShowAllCategories:YES isSelectAllCategories:self.selectCategoryUniqueId == 0 hidesAllActions:NO];
}

- (void)handleCreateReceipt {
    if (self.selectRecordModel) {
        @weakify(self);
        [YYBViewRouter openOnClass:[MGReceiptController class] configureBlock:^(MGReceiptController *obj) {
            @strongify(self);
            obj.recordModel = self.selectRecordModel;
            obj.updateSuccBlock = ^{
                [self refreshData];
            };
        }];
    }
}

- (void)handleUpdateReceipt:(MGReceiptModel *)dataModel {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGReceiptController class] configureBlock:^(MGReceiptController *obj) {
        @strongify(self);
        obj.recordModel = self.selectRecordModel;
        obj.updateModel = dataModel;
        obj.updateSuccBlock = ^{
            [self refreshData];
        };
        obj.deleteSuccBlock = ^{
            [self refreshData];
        };
    }];
}

- (void)handleRecordsSelect {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGRecordsSelectController class] configureBlock:^(MGRecordsSelectController *obj) {
        @strongify(self);
        obj.updateRecordsBlock = ^{
            // 可能是删除账本
            self.shouldRemoveBottomInsets = YES;
            [self refreshData];
        };
        obj.changeRecordBlock = ^{
            [self refreshData];
        };
    }];
}

// 创建一个账本
- (void)handleCreateRecordModel {
    @weakify(self);
    [MGAlertView showRecordsTypeAlertViewWithTapedBlock:^(MGRecordType type) {
        [YYBViewRouter openOnClass:[MGRecordController class] configureBlock:^(MGRecordController *obj) {
            @strongify(self);
            obj.recordType = type;
            obj.createRecordModelBlock = ^{
                [self beginQueryData];
            };
        }];
    }];
}

// 修改小目标
- (void)updateRecordModelHandler {
    [YYBViewRouter openOnClass:[MGRecordController class] configureBlock:^(MGRecordController *obj) {
        
    }];
}

// 打卡详情页面
- (void)handleReceiptModel:(MGReceiptModel *)receiptModel {
    @weakify(self);
    if (receiptModel.receiptType == MGReceiptTypePunch) {
        [YYBViewRouter openOnClass:[MGPunchController class] configureBlock:^(MGPunchController *obj) {
            obj.updateModel = receiptModel;
            obj.updateSuccBlock = ^{
                @strongify(self);
                [self refreshData];
            };
        }];
    } else {
        [YYBViewRouter openOnClass:[MGReceiptController class] configureBlock:^(MGReceiptController *obj) {
            obj.updateModel = receiptModel;
            obj.updateSuccBlock = ^{
                @strongify(self);
                [self refreshData];
            };
        }];
    }
}

// =================================================================================
- (void)createAccount {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGAccountController class] configureBlock:^(MGAccountController *obj) {
        @strongify(self);
        obj.deleteModelBlock = ^(NSUInteger uniqueId) {
            if (self.selectAccountUniqueId == uniqueId || self.selectAccountUniqueId == 0) {
                [self refreshData];
            }
        };
        obj.updateModelBlock = ^(NSUInteger uniqueId) {
            if (self.selectAccountUniqueId == uniqueId || self.selectAccountUniqueId == 0) {
                [self refreshData];
            }
        };
    }];
}

- (void)getIntoAccountList {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGAccountsController class] configureBlock:^(MGAccountsController *obj) {
        @strongify(self);
        obj.deleteModelBlock = ^(NSUInteger uniqueId) {
            if (self.selectAccountUniqueId == uniqueId || self.selectAccountUniqueId == 0) {
                [self refreshData];
            }
        };
        obj.updateModelBlock = ^(NSUInteger uniqueId) {
            if (self.selectAccountUniqueId == uniqueId || self.selectAccountUniqueId == 0) {
                [self refreshData];
            }
        };
    }];
}

- (void)createCategory {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGCategoryController class] configureBlock:^(MGCategoryController *obj) {
        @strongify(self);
        obj.deleteModelBlock = ^(NSUInteger uniqueId) {
            if (self.selectCategoryUniqueId == uniqueId || self.selectCategoryUniqueId == 0) {
                [self refreshData];
            }
        };
        obj.updateModelBlock = ^(NSUInteger uniqueId) {
            if (self.selectCategoryUniqueId == uniqueId || self.selectCategoryUniqueId == 0) {
                [self refreshData];
            }
        };
    }];
}

- (void)getIntoCategoryList {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGCategoriesController class] configureBlock:^(MGCategoriesController *obj) {
        @strongify(self);
        obj.deleteModelBlock = ^(NSUInteger uniqueId) {
            if (self.selectCategoryUniqueId == uniqueId || self.selectCategoryUniqueId == 0) {
                [self refreshData];
            }
        };
        obj.updateModelBlock = ^(NSUInteger uniqueId) {
            if (self.selectCategoryUniqueId == uniqueId || self.selectCategoryUniqueId == 0) {
                [self refreshData];
            }
        };
    }];
}

- (NSArray<NSString *> *)dequeueCellIdentifiers {
    return @[
        @"MGRecordsReceiptCell",
        @"MGRecordsDateCell",
        @"MGReceiptEmptyCell"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return MAX(1, self.sortedReceiptModels.count);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.sortedReceiptModels.count == 0) {
        return 1; // 空数据提示
    } else {
        MGReceiptDateModel *dataDateModel = self.sortedReceiptModels[section];
        return dataDateModel.dataModels.count + 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.sortedReceiptModels.count == 0) {
        return 300; // 空数据提示
    } else {
        if (indexPath.row == 0) {
            return 40;
        }
        MGReceiptDateModel *dataDateModel = self.sortedReceiptModels[indexPath.section];
        MGReceiptModel *dataModel = dataDateModel.dataModels[indexPath.row - 1];
        return [MGRecordsReceiptCell queryViewHeightWithDataModel:dataModel];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.sortedReceiptModels.count == 0) {
        MGReceiptEmptyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGReceiptEmptyCell"];
        return cell;
    } else {
        MGReceiptDateModel *dataDateModel = self.sortedReceiptModels[indexPath.section];
        if (indexPath.row == 0) {
            MGRecordsDateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGRecordsDateCell"];
            
            NSDictionary *dict = [dataDateModel getMoneyValuesWithRecordModel:self.selectRecordModel accountUniqueId:self.selectAccountUniqueId categoryUniqueId:self.selectCategoryUniqueId];
            NSDecimalNumber *incomeMoney = dict[@"incomeMoney"];
            NSDecimalNumber *paidMoney = dict[@"paidMoney"];
            
            [cell configViewWithDataModel:dataDateModel incomeMoney:incomeMoney paidMoney:paidMoney];
            return cell;
        }
        
        MGRecordsReceiptCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGRecordsReceiptCell"];

        MGReceiptModel *dataModel = dataDateModel.dataModels[indexPath.row - 1];
        [cell configViewWithDataModel:dataModel];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.sortedReceiptModels.count > 0 && indexPath.row != 0) {
        MGReceiptDateModel *dataDateModel = self.sortedReceiptModels[indexPath.section];
        MGReceiptModel *dataModel = dataDateModel.dataModels[indexPath.row - 1];
        
        [self handleUpdateReceipt:dataModel];
    }
}

- (BOOL)hidesBottomBarWhenPushed {
    return NO;
}

@end
